import React, { Component } from 'react'
import {
  StyleSheet,
  ScrollView,
  View,
  Text,
  TextInput,
  KeyboardAvoidingView,
  Image,
  TouchableWithoutFeedback
} from 'react-native'
import { connect } from 'react-redux'

import Toast from 'react-native-simple-toast'
import { theme_app, theme_text, theme_btnColor } from '../../utils/appTheme'
import HeaderDefault from '../../components/header/HeaderDefault'
import { dateTransform } from '../../utils/commonMethod'

import Button from '../../components/Button'
import { addBill } from '../../netServer/signs_net'

class FeeSings extends Component {
  constructor(props) {
    super(props)
    this.state = {
      jifeinum: '',
      totalMoney: '',
      cash_money: '',
      enntry_date: new Date(),
      project: null
    }
    this.callBack = this.callBack.bind(this)
    this._commitBtn = this._commitBtn.bind(this)
  }
  static navigationOptions = ({ navigation }) => ({
    gesturesEnabled: false,
    header: (
      <HeaderDefault
        title="费用录入"
        backBtnOnPress={() => {
          // navigation.navigate('Home')
          navigation.goBack(navigation.state.params.currentRouterKey)
        }}
      />
    )
  })

  callBack(item) {
    let mNum = parseFloat(this.state.jifeinum)
    let price = item.PRICE * mNum
    if (isNaN(price)) {
      price = 0
    }
    this.setState({
      project: item,
      totalMoney: price.toString()
    })
  }

  // 录入信息
  _renderInputItem1(
    tilteStr,
    textInputChange,
    inputeValue,
    placeholderStr,
    unitstr,
    keyboardTypeS = 'default'
  ) {
    return (
      <View style={styles.inputItem1}>
        <Text style={{ width: 70 }}>{tilteStr}</Text>
        <TextInput
          style={styles.textInput}
          placeholder={placeholderStr}
          placeholderTextColor="rgb(206,206,211)"
          onChangeText={textInputChange}
          value={inputeValue}
          keyboardType={keyboardTypeS}
          underlineColorAndroid="transparent"
          selectionColor="rgb(35,151,246)"
          clearButtonMode="while-editing"
        />

        <Text style={{ width: 60, textAlign: 'right' }}>{unitstr}</Text>
      </View>
    )
  }

  // 床号、姓名、年龄、性别
  _renderInputItem2(title1, titele2, value1, value2) {
    return (
      <View style={styles.inputItem1}>
        <View style={{ flex: 1, flexDirection: 'row' }}>
          <Text style={{ width: 50 }}>{title1}</Text>
          <Text style={{ color: theme_text.default_Color }}>{value1}</Text>
        </View>
        <View style={{ flex: 1, flexDirection: 'row' }}>
          <Text style={{ width: 50 }}>{titele2}</Text>
          <Text style={{ color: theme_text.default_Color }}>{value2}</Text>
        </View>
      </View>
    )
  }

  // 疗养号
  _renderInputItem3(title1, value1) {
    return (
      <View style={styles.inputItem1}>
        <Text style={{ width: 70 }}>{title1}</Text>
        <Text style={{ color: theme_text.default_Color }}>{value1}</Text>
      </View>
    )
  }

  _renderInputItem4(tilteStr, value) {
    return (
      <TouchableWithoutFeedback
        onPress={() => {
          this.props.navigation.navigate('FeeProList', {
            callback: this.callBack
          })
        }}
      >
        <View style={styles.inputItem1}>
          <Text style={{ width: 70 }}>{tilteStr}</Text>
          <Text style={styles.selectCell}>
            {value ? value.ITEMNAME : '请选择项目'}
          </Text>

          <Image
            source={require('./src/youjiantou.png')}
            style={{ width: 40, height: 40 }}
          />
        </View>
      </TouchableWithoutFeedback>
    )
  }

  componentDidMount() {}

  _commitBtn() {
    if (!this.state.project) {
      Toast.showWithGravity('请选择计费项目', 0.3, Toast.CENTER)
      return
    }

    let mNum = parseFloat(this.state.jifeinum)
    if (mNum <= 0 || isNaN(mNum)) {
      Toast.showWithGravity('请输入计费数量', 0.3, Toast.CENTER)
      return
    }

    let params = new FormData()
    params.append('user_id', this.props.user_info.user_id)
    params.append('patient_no', this.props.navigation.state.params.pno)
    params.append('his_item_id', this.state.project.ID)
    params.append('discount', 0)
    params.append('item_name', this.state.project.ITEMNAME)

    params.append('unit', this.state.project.UNIT)
    params.append(
      'record_date',
      dateTransform(this.state.enntry_date, 'yyyy-MM-dd hh:mm:ss')
    )
    params.append('price', this.state.project.PRICE)
    params.append('measure', this.state.jifeinum)
    params.append('record_money', this.state.totalMoney)
    params.append('cash_money', this.state.cash_money)

    addBill(params, resp => {
      let { code, data, msg } = resp
      if (code == '0') {
        this.setState({
          jifeinum: '',
          totalMoney: '',
          cash_money: '',
          enntry_date: new Date(),
          project: null
        })
        Toast.showWithGravity('提交成功', 0.3, Toast.CENTER)
      } else {
        Toast.showWithGravity(msg, 0.3, Toast.CENTER)
      }
    })
  }
  render() {
    return (
      <KeyboardAvoidingView
        keyboardVerticalOffset={100}
        behavior="padding"
        style={{ flex: 1 }}
      >
        <ScrollView
          keyboardShouldPersistTaps="always"
          keyboardDismissMode="on-drag"
          style={{ flex: 1, backgroundColor: theme_app.bg_color }}
          contentContainerStyle={styles.container}
        >
          <View>
            <View style={{ height: 10 }} />
            {this._renderInputItem4('计费项目', this.state.project)}
            {this._renderInputItem3(
              '计费时间',
              dateTransform(this.state.enntry_date, 'yyyy-MM-dd hh:mm')
            )}
            {this._renderInputItem3(
              '计费单位',
              this.state.project ? this.state.project.UNIT : ''
            )}
            {this._renderInputItem3(
              '单价金额',
              this.state.project ? this.state.project.PRICE : ''
            )}

            {this._renderInputItem1(
              '计费数量',
              text => {
                this.setState({ jifeinum: text })
                let mNum = parseFloat(text)
                if (this.state.project) {
                  let price = this.state.project.PRICE * mNum
                  if (isNaN(price)) {
                    price = 0
                  }
                  this.setState({ totalMoney: price.toString() })
                }
              },
              this.state.jifeinum,
              '请输入数量',
              '',
              'numeric'
            )}

            {this._renderInputItem1(
              '现金金额',
              text => {
                this.setState({ cash_money: text })
              },
              this.state.cash_money,
              '请输入现金金额',
              '',
              'numeric'
            )}

            {this._renderInputItem3('总金额', this.state.totalMoney)}

            <View
              style={{
                width: screenWidth,
                height: 60,
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <Button
                style={[
                  styles.buttonCommit,

                  { backgroundColor: theme_btnColor.main_color }
                ]}
                onPress={this._commitBtn}
              >
                <Text
                  style={{
                    fontSize: 18,
                    color: theme_text.background_Color
                  }}
                >
                  提交
                </Text>
              </Button>
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: theme_app.bg_color
  },
  inputItem1: {
    flexDirection: 'row',
    width: screenWidth,
    height: 45,
    backgroundColor: 'white',
    borderBottomColor: theme_app.separationLine_color,
    borderBottomWidth: 1,
    paddingLeft: 15,
    paddingRight: 15,
    alignItems: 'center'
  },
  textInput: {
    // backgroundColor: 'green',
    color: 'gray',
    fontSize: theme_text.default_font,
    alignSelf: 'center',
    width: screenWidth - 170,
    height: 40
  },
  selectCell: {
    // backgroundColor: 'green',
    color: 'gray',
    fontSize: theme_text.default_font,
    alignSelf: 'center',
    width: screenWidth - 130,
    height: 40,
    lineHeight: 40
  },
  buttonCommit: {
    width: 200,
    // height: 46,
    borderRadius: 6
  }
})

function select(store) {
  return {
    user_info: store.userInfo.user_info
  }
}

export default connect(select)(FeeSings)
